package im

import (
	"fmt"
	"time"
	"strings"
	"errors"
	"dhfshop/models"
	"dhfshop/utils/uuid"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 双方聊天记录存储表
type ChatRecord struct {
	ChatRecordId    int64     `orm:"column(chat_record_id);pk" json:"chat_record_id,string" form:"-"`
	PartnerId       int64     `orm:"column(partner_id);index" json:"partner_id"`                            //组织ID
	AppId           string    `orm:"column(app_id);size(32)" json:"app_id" form:"app_id"`                            //托管的公众号ID
	ChatSessionId   int64     `orm:"column(chat_session_id)" json:"chat_session_id" form:"chat_session_id"` //会话ID
	MemberOpenId    string    `orm:"column(member_open_id)" json:"member_open_id" form:"member_open_id"`    //顾客open_id
	AgentOpenId     string    `orm:"column(agent_open_id);null" json:"agent_open_id" form:"agent_open_id"`  //客服open_id     
	MsgId           string    `orm:"column(msg_id)" json:"msg_id" form:"msg_id"`                  //微信消息ID,收到客户消息有效，客服发送则无效
	MsgType         string    `orm:"column(msg_type)" json:"msg_type" form:"msg_type"`            //微信消息类型,text,image,link,miniprogrampage
	MsgTime         time.Time `orm:"auto_now_add;column(msg_time);type(datetime)" json:"-" form:"-"`  //消息产生时间    
	SendBy          int       `orm:"column(send_by)" json:"send_by" form:"send_by"`               //消息产生者：1:顾客; 2: 客服
	Content         string    `orm:"column(content);type(text)" json:"content" form:"content"`    //消息内容
	MediaId         string    `orm:"column(media_id)" json:"media_id" form:"media_id"`            //image消息关联的图片ID
	Link            string    `orm:"column(link);type(text)" json:"link" form:"link"`             //link类型消息json串
	MsgBody         string    `orm:"column(msg_body);type(text);null" json:"msg_body" form:"msg_body"` //存放消息内容或者事件内容(JSON字符串格式)
	StatusId        int       `orm:"column(status_id)" json:"status_id" form:"status_id"`         //消息状态ID, 1:未读, 2 已读
	// 非数据库字段
	MsgTimeStr      string    `orm:"-" json:"msg_time" form:"msg_time"`
	FormId          string    `orm:"-" json:"-" form:"form_id"`          
}

func init() {
	orm.RegisterModel(new(ChatRecord))
}

func AddChatRecord(m *ChatRecord) (id int64, err error) {
	m.ChatRecordId, err = uuid.GetSnowFlakeId(uuid.Worker)
	if err != nil {
	    return
	}
	o := models.GetDefaultDB()
	_, err = o.Insert(m)
	id = m.ChatRecordId
	return id, err
}

func GetAllChatRecords(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*ChatRecord,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ChatRecord))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ChatRecord
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, record := range lists {
			record.MsgTimeStr = record.MsgTime.Format(consts.DATETIME_FORMAT)
		}
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetChatRecordById(id int64) (v *ChatRecord, err error) {
	o := models.GetDefaultDB()
	v = &ChatRecord{ChatRecordId: id}
	if err = o.Read(v); err == nil {
		v.MsgTimeStr = v.MsgTime.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}

func GetUnreadMessage(partnerId int64) (records []*ChatRecord, err error) {
	records = []*ChatRecord{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ChatRecord)).OrderBy("-chat_record_id").Filter("partner_id", partnerId).Filter("status_id", 1)
	_, err = qs.All(&records)
	for _, record := range records {
		record.MsgTimeStr = record.MsgTime.Format(consts.DATETIME_FORMAT)
	}
	return
}

func UpdateChatRecordById(m *ChatRecord,param ... string) (err error) {
	o := models.GetDefaultDB()
	v := ChatRecord{ChatRecordId: m.ChatRecordId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, param...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteChatRecord(id int64) (err error) {
	o := models.GetDefaultDB()
	v := ChatRecord{ChatRecordId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}


